package cn.innosmart.aq.application;

import android.app.Activity;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.crashlytics.android.Crashlytics;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
import com.tutk.P2PCam264.MyCamera;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECInitParams;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.kitsdk.ECDeviceKit;
import com.yuntongxun.kitsdk.beans.ECAuthParameters;
import com.yuntongxun.kitsdk.core.CCPAppManager;
import com.yuntongxun.kitsdk.listener.OnConnectSDKListener;
import com.yuntongxun.kitsdk.listener.OnInitSDKListener;
import com.zhy.autolayout.config.AutoLayoutConifg;

import io.fabric.sdk.android.Fabric;
import java.io.File;

import cn.innosmart.aq.BuildConfig;
import cn.innosmart.aq.R;
import cn.innosmart.aq.util.AppUtil;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.FakeX509TrustManager;
import cn.innosmart.aq.util.LocationUtil;
import cn.innosmart.aq.util.SystemConstant;

/**
 * Created by David on 2015/7/6.
 */
public class AQApplication extends Application {

    public static RequestQueue mQueue;
    private static AQApplication instace;
    public Activity mActivity;
    private String Tag = "AQApplication";
    private Toast mToast;

    /**
     * Application
     *
     * @return AQApplication
     */
    public static AQApplication getInstance() {
        return instace;
    }

    /**
     * 根据Type获得图片的资源
     *
     * @param ctx
     * @param channelType
     * @return
     */
    public static int getChannelDrawableRes(Context ctx, int channelType) {
        StringBuilder sb = new StringBuilder();
        switch (channelType) {
            case DeviceConstant.FUNCTYPE_TEMPERATURE:
                sb.append("temperature");
                break;
            case DeviceConstant.FUNCTYPE_PH:
                sb.append("ph");
                break;
            case DeviceConstant.FUNCTYPE_WATERLEVER:
                sb.append("water_lever");
                break;
            case DeviceConstant.FUNCTYPE_SWITCH:
                sb.append("switch");
                break;
            case DeviceConstant.FUNCTYPE_FEEDER:
                sb.append("feed");
                break;
            default:
                sb.append("switch");
                break;
        }
        sb.append("_icon");
        return ctx.getResources().getIdentifier(sb.toString(), "drawable", ctx.getPackageName());
    }

    private void initImageLoader() {
        File cacheDir = StorageUtils.getOwnCacheDirectory(
                getApplicationContext(), "AQ/image");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                this).threadPoolSize(1)
                // 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .memoryCache(new WeakMemoryCache())
                // .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(CCPAppManager.md5FileNameGenerator)
                // 将保存的时候的URI名称用MD5 加密
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .diskCache(new UnlimitedDiscCache(cacheDir, null,
                        CCPAppManager.md5FileNameGenerator))// 自定义缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                // .writeDebugLogs() // Remove for release app
                .build();// 开始构建
        ImageLoader.getInstance().init(config);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Fabric.with(this, new Crashlytics());
        instace = this;
//        CrashHandler.getInstance().init(getApplicationContext());
        AutoLayoutConifg.getInstance().useDeviceSize();
        initXinGe();
        initVolley();
        //初始化设备名称映射表
        initNameMap();
        //初始化分享功能
        initShare();
        //初始化摄像头功能
        initCamera();
        //初始化图片加载缓存
        initImageLoader();
        //初始化百度地图SDK
        LocationUtil.getInstance().initLocationUtil(getApplicationContext());
        //开始定位
        LocationUtil.getInstance().startLocation();
    }


    /**
     * 初始化摄像头，一定要，否则播放会提示连接失败
     */
    private void initCamera() {
        if (!AppUtil.getInstance().isEmulator()) {
            int Code = MyCamera.init();
        }
    }

    /**
     * 初始化信鸽
     */
    private void initXinGe() {
        XGPushManager.registerPush(getApplicationContext(), new XGIOperateCallback() {
            @Override
            public void onSuccess(Object o, int i) {
                logW("XinGe Regist Success:" + o.toString());
            }

            @Override
            public void onFail(Object o, int i, String s) {
                logW("XinGe Regist Fail:" + o.toString());
            }
        });
    }

    private void initVolley() {
        mQueue = Volley.newRequestQueue(getApplicationContext());
        //此方法 为  允许所有的HTTPS请求
        FakeX509TrustManager.allowAllSSL();
    }

    private void initNameMap() {
        DeviceConstant.nameMap.put("O2 Switch", getString(R.string.aq_namemap_switch_o2));
        DeviceConstant.nameMap.put("Water Switch", getString(R.string.aq_namemap_switch_water));
        DeviceConstant.nameMap.put("Light Switch", getString(R.string.aq_namemap_switch_light));
        DeviceConstant.nameMap.put("Feed Switch", getString(R.string.aq_namemap_switch_feed));
        DeviceConstant.nameMap.put("Water Level Sensor", getString(R.string.aq_namemap_water_lever));
        DeviceConstant.nameMap.put("Water Temperature", getString(R.string.aq_namemap_temperature));
        DeviceConstant.nameMap.put("PH", getString(R.string.aq_namemap_ph));
        DeviceConstant.nameMap.put("Switch", getString(R.string.aq_namemap_switch));
        DeviceConstant.nameMap.put("Simple Feeder Trigger", getString(R.string.aq_namemap_feed));
    }

    private void initShare() {
        String appId = BuildConfig.WXAPPID;
        String appSecret = BuildConfig.WXAPPSECRET;
        // 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(this, appId, appSecret);
        wxHandler.addToSocialSDK();
        // 添加微信朋友圈
        UMWXHandler wxCircleHandler = new UMWXHandler(this, appId, appSecret);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
    }

    /**
     * 获取版本号
     *
     * @return 异常返回-1，否则返回版本号
     */
    public int getVersionCode() {
        PackageManager manager = getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            int currentVersionCode = info.versionCode;
            return currentVersionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 获取app版本名称
     *
     * @return 异常返回null，否则返回版本名称
     */
    public String getVersionName() {
        PackageManager manager = getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            String appVersion = info.versionName;
            return appVersion;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取mqtt连接的clientId
     *
     * @return
     */
    public String getMqttClientId() {
        String id = null;
        SharedPreferences sp = getSharedPreferences("MQTT", MODE_PRIVATE);
        id = sp.getString("client_id", null);
        if (null == id) {
            id = generateUniqueId();
            SharedPreferences.Editor edit = sp.edit();
            id = "g1_" + id;
            edit.putString("client_id", id);
            edit.commit();
        }
        return id;
    }

    /**
     * 获取设备唯一ID
     *
     * @return
     */
    private String generateUniqueId() {
        String id = null;
        String szImei = "";
        String szAndroidID = "";
        String szWLANMAC = "";
        String szBTMAC = "";

        do {
            try {
                szAndroidID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                id = szAndroidID;
                break;
            } catch (Exception e) {
            }

            try {
                TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                szImei = TelephonyMgr.getDeviceId();
                id = szImei;
                break;
            } catch (Exception e) {
            }

            try {
                WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                szWLANMAC = wm.getConnectionInfo().getMacAddress()
                        .replace(":", "");
                id = szWLANMAC;
                break;
            } catch (Exception e) {
            }

            try {
                BluetoothAdapter m_BluetoothAdapter = null;
                m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                szBTMAC = m_BluetoothAdapter.getAddress().replace(":", "");
                id = szBTMAC;
                break;
            } catch (Exception e) {
            }
        } while (false);

        if (id.length() > 20)
            id = id.substring(0, 20);

        return id;
    }

    private void logV(String msg) {
        Log.v(Tag, msg);
    }

    private void logW(String msg) {
        Log.w(Tag, msg);
    }


    /**
     * 初始化IM
     *
     * @param userId
     * @param nickname
     */
    public void initIM(final String userId, String nickname) {
        ECDeviceKit.init(userId, this, new OnInitSDKListener() {
            @Override
            public void onInitialized() {
                connectIM(userId);
            }

            @Override
            public void onError(Exception exception) {
                System.out.println("Init Error!");
            }
        });
        ECDeviceKit.getInstance().setNickName(nickname);
    }

    /**
     * 连接IM
     *
     * @param userId
     */
    public void connectIM(final String userId) {
        ECAuthParameters parameters = new ECAuthParameters();
        parameters.setAppKey("8a48b5514e236232014e2d3d4123091f");
        parameters.setUserId(userId);
        parameters.setAppToken("61afb68b8191bf22588ef22dcddbd4c7");
        parameters.setLoginMode(ECInitParams.LoginMode.FORCE_LOGIN);
        parameters.setLoginType(ECInitParams.LoginAuthType.NORMAL_AUTH);
        ECDeviceKit.login(parameters, new OnConnectSDKListener() {
            @Override
            public void onDisconnect(ECError error) {
                // 兼容4.0
//                showToast("onDisconnect="+error.errorCode);
            }

            @Override
            public void onConnectState(ECDevice.ECConnectState state, ECError error) {
                // 获取当前sdk的连接状态
                if (state == ECDevice.ECConnectState.CONNECT_FAILED) {
                    if (error.errorCode == SdkErrorCode.SDK_KICKED_OFF) {
                        //帐号异地登陆
//                        showToast("帐号异地登陆!");
                    } else {
                        //连接状态失败
                        System.out.println("登录失败!");
//                        showToast("聊天登陆失败!"+error.errorCode);
                    }
                    return;
                } else if (state == ECDevice.ECConnectState.CONNECT_SUCCESS) {
                    // 登陆成功
                    System.out.println("登录成功!");
                }
            }

            @Override
            public void onConnect() {
                // 兼容4.0
                System.out.println("Connect IM");
            }
        });
    }
}
